package com.mryan.ps_auth.configure;

import com.mryan.ps_auth.filter.ValidateCodeFilter;
import com.mryan.ps_auth.service.PSUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_auth.configure
 * @Author: Yan
 * @CreateTime: 2021-04-23 20:56
 * @Description: 用于处理和令牌相关的请求
 */
@Order(2)
@Configuration
@EnableWebSecurity
public class PSSecurityConfigure extends WebSecurityConfigurerAdapter {

	@Autowired
	private PSUserDetailService userDetailService;
	@Autowired
	private ValidateCodeFilter validateCodeFilter;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
				.requestMatchers()
				.antMatchers("/oauth/**")
				.and()
				.authorizeRequests()
				.antMatchers("/oauth/**").authenticated()
				.and()
				.csrf().disable();
	}
}
